#!/usr/bin/env python

import os, matplotlib, numpy, fcsextract, sys
			


# Function to import all the tube files annotated in the description file
def importTubes(descFile):
	allTubes = []
	desc = open('/Users/ucsf/Documents/Team_challenge/cytometry/cytomScripts/source_control/' + descFile)
	for i,line in enumerate(desc.readline().split('\r')):
		if i == 0:
			fields = line.strip().split('\t')
		else:
			tubeIndex = len(allTubes)
			tempTube = Tube(line.strip().split('\t'), fields)
			allTubes.append(tempTube)
	return allTubes

# Function to return tubes that you have searched for
# searchTermList is fields you want to search through
# searchTermValues is the values for each field you want
def returnTubes(searchTermList, searchTermValues, tubeList):
	print 'length of tubeList in call: ' + str(len(tubeList))
	retList = []
	for tube in tubeList:
		for i,term in enumerate(searchTermList):
			if getattr(tube, term) != searchTermValues[i]:
				break
			else:
				if i == len(searchTermList) -1:
					retList.append(tube)
	return retList

# interperets one single tube (or well) as an object
# arguements are:
# fileInfo: a line from your description file (as a List)
# fields: a list of the fields that you have (ex: ['files', 'concentrations' ...]
class Tube:
	def __init__(self, fileInfo, fields):
		fieldDict = {}
		for i,item in enumerate(fields):
			fieldDict[item] = i

	
		fileName = fileInfo[fields.index('files')]
		writeIn1,writeIn2 = fcsextract.fcsextract('/Users/ucsf/Documents/Team_challenge/cytometry/cytomScripts/source_control/sample_data/' + fileName)
		fcsextract.writefcs(writeIn1,writeIn2,fileName)
		name = fileName.split('.')[0]
		
		#read header file to account for format differences between CAT and class outputs
		#header file is the filename with a .info ending
		hdrFile = str(name) + '.info'
		hdr = open(hdrFile, 'r')
		indexDict = {}
		for i,line in enumerate(hdr.readlines()):
			indexDict[line.split('\t')[0]] = i
		
		#initialize object with data from run
		#data is in filename with a .csv ending
		dataFile = str(name) + '.csv'
		dataMat= []
		myFile = open(dataFile, 'r')
		for line in myFile:
			line = line.strip().split(',')
			dataMat.append([float(element) for element in line])
		dataMat=numpy.array(dataMat)
		
		#add each vector of values to field list
		self.FSC_A = dataMat[:,indexDict['FSC-A']]
		self.SSC_A = dataMat[:,indexDict['SSC-A']]
		self.FITC_A = dataMat[:,indexDict['FITC-A']]
		self.Time = dataMat[:][indexDict['Time']]
		self.meanFITC_A = numpy.mean(self.FITC_A)
		self.medianFITC_A = numpy.median(self.FITC_A)
		self.stdFITC_A = numpy.std(self.FITC_A)

		#initialize custom fields
		for field in fields:
			setattr(self, field, fileInfo[fieldDict[field]])



###########################################################################			
###########################################################################
###########################################################################
###########################################################################

class Replicate:
	def __init__(self, tubeList):
		for tube in tubeList:
			self.tubes.append(tubeList[tube])
			self.meanList.append(tubeList[tube].meanFITC_A)
			self.medianList.append(tubeList[tube].medianFITC_A)
		self.stdMean = numpy.std(self.meanList)
		self.stdMedian = numpy.std(self.medianList)	

#function to sort chemicals	
def sortChem(tubeList):
	chemDict = {}
	for tube in tubeList:
		if tube.chemical in chemDict:
			chemDict[tube.chemical].append(tube)
		else:
			chemDict[tube.chemical] = []
			chemDict[tube.chemical].append(tube)
	return chemDict
		
def sortStrain(tubeList):
	strainDict = {}
	for tube in tubeList:
		if tube.strain in strainDict:
			strainDict[tube.strain].append(tube)
		else:
			strainDict[tube.strain] = []
			strainDict[tube.strain].append(tube)
	return strainDict
			
class Chemical:
	def __init__(self, chemical, chemList):
		self.chemical = chemical
		self.chemList = chemList
		


#read all the cytometry data files in folder
#fileList = os.listdir('/Users/ucsf/Documents/Team_challenge/cytometry')
#for file in fileList:
#	if '.txt' in file and 'Specimen_' in file:
		
